package com.zgt.util;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Calendar;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class ExcelUtil {

	public static void setCellValue(HSSFSheet sheet, int colNum, int rowNum,
			String value) {
		HSSFRow row = sheet.getRow(rowNum);
		if (row == null) {
			row = sheet.createRow(rowNum);
		}

		HSSFCell cell = (HSSFCell) row.getCell(colNum);

		cell = (cell == null) ? row.createCell(colNum) : cell;

		if (value != null) {
			cell.setCellValue(value);
		} else {
			cell.setCellType(HSSFCell.CELL_TYPE_BLANK);
		}
	}

	public static void createTitle(HSSFSheet sheet, String[] strTitle) {
		HSSFRow row = sheet.createRow(0);
		HSSFCell cell = null;

		for (int i = 0; i < strTitle.length; i++) {
			cell = row.createCell(i);
			cell.setCellType(HSSFCell.CELL_TYPE_STRING);
			cell.setCellValue(strTitle[i]);
		}
	}

	public static void print2003Excel(HSSFWorkbook wb,
			HttpServletResponse response, String key, String keyType)
			throws IOException {
		Calendar now = Calendar.getInstance();
		String time = now.get(Calendar.YEAR) + "-"
				+ (now.get(Calendar.MONTH) + 1) + "-"
				+ now.get(Calendar.DAY_OF_MONTH) + " "
				+ now.get(Calendar.HOUR_OF_DAY) + ":" 
				+ now.get(Calendar.MINUTE)
				+ ":" + now.get(Calendar.SECOND) + ":"
				+ now.get(Calendar.MILLISECOND);
		if (key != null && keyType != null) {
			time += " "+key;
		}
		String fileName = time + ".xls";
		OutputStream out = response.getOutputStream();
		response.setHeader("Content-disposition", "attachment; filename="
				+ fileName);
		response.setContentType("application/vnd.ms-excel;charset=UTF-8");
		wb.write(out);
		out.flush();
		out.close();
		out = null;

	}

}
